package com.yang.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yang.dto.req.CommodityPageQueryReqDTO;
import com.yang.dto.req.CommoditySaveReqDTO;
import com.yang.dto.req.CommodityUpdateReqDTO;
import com.yang.dto.resp.CommodityPageQueryRespDTO;
import com.yang.result.Result;
import com.yang.service.CommodityService;
import com.yang.utils.AliOssUtil;
import com.yang.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;

/**
 * 商品控制层
 * 作者：孤城暖阳y
 * 日期：2025-03-03
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "商品管理")
public class CommodityController {

    private final CommodityService commodityService;

    @Operation(summary = "分页查询商品详情")
    @GetMapping("/Treasure-Pavilion-admin/commodity/page")
    public Result<IPage<CommodityPageQueryRespDTO>> findAll(CommodityPageQueryReqDTO requestParam) {
        return Result.success(commodityService.pageQueryCommodities(requestParam));
    }

    @Operation(summary = "添加商品")
    @PostMapping("/Treasure-Pavilion-admin/commodity/save")
    public Result saveCommodity(@Valid @RequestBody CommoditySaveReqDTO requestParam) {
        // TODO 等待具体实现service
        commodityService.saveCommodity(requestParam);
        return Result.success();
    }

    @Operation(summary = "上传商品封面")
    @PostMapping("/Treasure-Pavilion-admin/commodity/uploadAvatar")
    public Result uploadAvatar(MultipartFile file) throws Exception {
        // 把文件存入到本地磁盘
        String originalFilename = file.getOriginalFilename();
        // 保证文件名称是唯一，防止文件覆盖
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = AliOssUtil.uploadFile("commodity/" + fileName, file.getInputStream());
        // 返回文件路径
        return Result.success(url);
    }

    @Operation(summary = "更新商品信息")
    @PutMapping("/Treasure-Pavilion-admin/commodity/update")
    public Result updateCommodity(@Valid @RequestBody CommodityUpdateReqDTO requestParam) {
        commodityService.updateCommodity(requestParam);
        return Result.success();
    }

    @Operation(summary = "删除商品")
    @DeleteMapping("/Treasure-Pavilion-admin/commodity/delete/{id}")
    public Result deleteCommodity(@PathVariable Long id) throws Exception {
        commodityService.deleteCommodity(id);
        return Result.success();
    }

}
